package 内地居民结婚登记数占比;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;

public class MarriageRatioReducer extends Reducer<Text, MarriageRatioBean, Text, MarriageRatioBean> {
    MarriageRatioBean outValue = new MarriageRatioBean();

    @Override
    protected void reduce(Text key, Iterable<MarriageRatioBean> values, Reducer<Text, MarriageRatioBean, Text, MarriageRatioBean>.Context context) throws IOException, InterruptedException {
        /**
         * 创建统计变量
         */
        float summarriageCount = 0;
        float sumfirstmarriageCount = 0;
        float sumremarriageCount = 0;
        double marriageRation = 0;
        double marriageRation1 = 0;

        // 遍历迭代器，累加结婚登记对数和再婚登记对数
        for (MarriageRatioBean value : values) {
            summarriageCount += value.getMarriageCount();
            sumfirstmarriageCount += value.getFirstmarriageCount();
            sumremarriageCount += value.getRemarriageCount();
        }

        // 计算初婚占比
        marriageRation = sumfirstmarriageCount / summarriageCount;
        // 使用String.format方法将离婚率结果保留两位小数
        String formattedmarriageRation = String.format("%.2f", marriageRation);
        marriageRation = Double.parseDouble(formattedmarriageRation);

        //计算再婚占比
        marriageRation1 = sumremarriageCount /summarriageCount;
        String formattedmarriageRation1 = String.format("%.2f", marriageRation1);
        marriageRation1 = Double.parseDouble(formattedmarriageRation1);
        /**
         * 输出结果赋值，这里假设DivorceRateBean类有相应的方法来设置离婚率等属性，你可根据实际情况调整
         */
        outValue.set(marriageRation,marriageRation1);
        context.write(key, outValue); // 输出的是 K    V
    }
}